<template>
  <div class="card-wrap flex-column justify-end card-padding" v-if="form.supplier">
    <el-form :model="form" :rules="type == 'detail' ? {} : rules" ref="supplierInformation" label-width="140px" :label-position="type == 'detail' ? 'right' : 'top'">
      <div class="card-title-wrap">
        <span>供应商信息</span>
        <span></span>
      </div>
      <!-- 供应商编辑模块 -->
      <div :style="{ marginLeft: type == 'detail' ? '' : '50px' }">
        <div style="display: flex; justify-content: start; align-items: center; flex-wrap: wrap; width: 100%; margin-top: 20px">
          <el-form-item label="供应商:" prop="supplier.supplierName" style="min-width: 33%">
            <el-input v-if="type !== 'detail'" style="width: 80%" v-model="form.supplier.supplierName" readonly @click.native="changeGys" placeholder="请选择供应商"></el-input>
            <span v-if="type == 'detail'">{{ form.supplier.supplierName }}</span>
          </el-form-item>
          <el-form-item label="授权期限:" prop="supplier.authorizationPeriod" style="min-width: 33%">
            <div v-if="type !== 'detail'">
              <!-- @input="form.supplier.authorizationPeriod = form.supplier.authorizationPeriod.replace(/^0|[^0-9]/g, '')" -->
              <el-input maxlength="8" @input="handleInput" style="max-width: 40%" v-model="form.supplier.authorizationPeriod" placeholder="请输入天数">
                <template slot="append">天</template>
              </el-input>
              <span style="margin-left: 10px"
                >{{ form.supplier.authorizationStartTime }} ~ <span v-if="form.supplier.authorizationPeriod" style="color: #1890ff">{{ form.supplier.authorizationEndTime }}</span></span
              >
            </div>
            <span v-if="type == 'detail'">{{ form.supplier.authorizationPeriod }} 天 {{ form.supplier.authorizationStartTime }} ~ {{ form.supplier.authorizationEndTime }}</span>
          </el-form-item>
          <el-form-item label="服务费-GPS正常:" prop="supplier.serviceFeeGpsNormal" style="min-width: 33%">
            <el-input
              v-if="type !== 'detail'"
              @input="form.supplier.serviceFeeGpsNormal = form.supplier.serviceFeeGpsNormal.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')"
              style="width: 80%"
              v-model="form.supplier.serviceFeeGpsNormal"
              maxlength="13"
              placeholder="请输入服务费-GPS正常"
            >
              <template slot="append">元/台</template>
            </el-input>
            <span v-if="type == 'detail'">10 元/台</span>
          </el-form-item>
          <el-form-item label="服务费-GPS异常:" prop="supplier.serviceFeeGpsAbnormal" style="min-width: 33%">
            <el-input
              v-if="type !== 'detail'"
              @input="form.supplier.serviceFeeGpsAbnormal = form.supplier.serviceFeeGpsAbnormal.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')"
              style="width: 80%"
              v-model="form.supplier.serviceFeeGpsAbnormal"
              maxlength="13"
              placeholder="请输入服务费单价"
            >
              <template slot="append">元/台</template>
            </el-input>
            <span v-if="type == 'detail'">{{ form.supplier.serviceFeeGpsAbnormal }} 元/台</span>
          </el-form-item>
          <el-form-item label="运输费:" prop="supplier.transportationFee" style="min-width: 33%">
            <el-input
              v-if="type !== 'detail'"
              @input="form.supplier.transportationFee = form.supplier.transportationFee.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')"
              style="width: 80%"
              v-model="form.supplier.transportationFee"
              maxlength="13"
              placeholder="请输入运输费"
            >
              <template slot="append">元/公里/台</template>
            </el-input>
            <span v-if="type == 'detail'">{{ form.supplier.transportationFee }} 元/公里/台</span>
          </el-form-item>
          <el-form-item label="仓储费:" prop="supplier.warehousingFee" style="min-width: 33%">
            <el-input
              v-if="type !== 'detail'"
              @input="form.supplier.warehousingFee = form.supplier.warehousingFee.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')"
              style="width: 80%"
              v-model="form.supplier.warehousingFee"
              maxlength="13"
              placeholder="请输入仓储费单价"
            >
              <template slot="append">元/天/台</template>
            </el-input>
            <span v-if="type == 'detail'">{{ form.supplier.warehousingFee }} 元/天/台</span>
          </el-form-item>
        </div>
        <el-form-item label="用印前合同信息:" prop="supplier.preContractInformation">
          <ImageCommon v-if="type !== 'detail'" :up-type="2" info="选择附件" :limit="5" v-model="form.supplier.preContractInformation"></ImageCommon>
          <ImageCommon v-if="type == 'detail'" v-model="form.supplier.preContractInformation" disabled></ImageCommon>
        </el-form-item>
        <el-form-item label="用印前授权书:" prop="supplier.preAuthorizationLetter">
          <ImageCommon v-if="type !== 'detail'" :up-type="2" info="选择附件" :limit="5" v-model="form.supplier.preAuthorizationLetter"></ImageCommon>
          <ImageCommon v-if="type == 'detail'" v-model="form.supplier.preAuthorizationLetter" disabled></ImageCommon>
        </el-form-item>
        <el-form-item label="其他附件:" prop="supplier.otherAttachments">
          <ImageCommon v-if="type !== 'detail'" :up-type="2" info="选择附件" :limit="5" v-model="form.supplier.otherAttachments"></ImageCommon>
          <ImageCommon v-if="type == 'detail'" :up-type="2" info="选择附件" v-model="form.supplier.otherAttachments" disabled></ImageCommon>
        </el-form-item>
      </div>
    </el-form>

    <!-- 添加或修改测试单表对话框 -->
    <el-dialog title="选择供应商" :visible.sync="open" append-to-body class="form-dialog" width="60%">
      <SearchContent :queryParams="queryParamsDig" @query="handleQueryDig" @reset="resetQueryDig">
        <el-form :model="queryParamsDig" label-width="100px">
          <el-col :span="9">
            <el-form-item label="供应商名称:" prop="supplierName">
              <el-input style="width: 100%" v-model="queryParamsDig.supplierName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="供应商类型:" prop="supplierTypeCode">
              <el-select filterable v-model="queryParamsDig.supplierTypeCode" clearable>
                <template v-for="dict in dict.type.supplier_type">
                  <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>
      </SearchContent>
      <el-row>
        <table-page ref="el-table" :loading="loading" :dataList="dataList" border :total="total" :page.sync="queryParamsDig.pageNum" :limit.sync="queryParamsDig.pageSize" @setSizeCurrent="getList">
          <!-- 操作插槽 -->
          <template slot="tableColAc">
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button type="text" @click="selectGys(scope.row)">选择供应商</el-button>
              </template>
            </el-table-column>
          </template>
          <!-- 普通列插槽 -->
          <template slot="tableCol">
            <el-table-column label="供应商编码" align="center" prop="supplierCode" min-width="140px" show-overflow-tooltip />
            <el-table-column label="供应商名称" align="center" prop="supplierName" min-width="200px" show-overflow-tooltip />
            <el-table-column show-overflow-tooltip min-width="100" label="供应商类型" align="center" prop="supplierType">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.supplier_type" :value="scope.row.supplierType" />
              </template>
            </el-table-column>
          </template>
        </table-page>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getSupplierList } from '@/api/pickUpTheCar'
import SearchContent from '@/components/SearchContent/index.vue'
export default {
  // 客户信息
  name: 'supplierInformation',
  dicts: ['supplier_type'],
  props: {
    value: {
      type: Object,
      default: {},
    },
    state: {
      type: String,
      default: '',
    },
  },
  components: {
    SearchContent,
  },
  computed: {
    form: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      },
    },
    type() {
      let status
      switch (this.state) {
        case 'write':
          status = 'edit'
          break
        case 'disabled':
          status = 'detail'
          break
        case 'readonly':
          status = 'detail'
          break
        case 'detail':
          status = 'detail'
          break
        case 'edit':
          status = 'edit'
        case 'add':
          status = 'add'
          break
      }
      return status
    },
  },
  watch: {
    'form.supplier.authorizationPeriod': {
      handler(val) {
        let authorizationEndTime = this.getFutureDate(val)
        this.form.supplier.authorizationEndTime = authorizationEndTime
      },
      deep: true,
    },
  },
  data() {
    return {
      dataList: [],
      loading: false,
      total: 0,
      open: false,
      queryParamsDig: {
        pageNum: 1,
        pageSize: 10,
        approvalStatus: 2,
      },
      rules: {
        supplier: {
          supplierName: [
            {
              required: true,
              message: '请选择供应商',
              trigger: 'change',
            },
          ],
          authorizationPeriod: [
            {
              required: true,
              message: '请输入授权期限',
              trigger: 'blur',
            },
          ],
          serviceFeeGpsNormal: [
            {
              required: true,
              message: '请输入服务费-GPS正常',
              trigger: 'blur',
            },
          ],
          serviceFeeGpsAbnormal: [
            {
              required: true,
              message: '请输入服务费-GPS异常',
              trigger: 'blur',
            },
          ],
          transportationFee: [
            {
              required: true,
              message: '请输入运输费',
              trigger: 'blur',
            },
          ],
          warehousingFee: [
            {
              required: true,
              message: '请输入仓储费',
              trigger: 'blur',
            },
          ],
          preContractInformation: [
            {
              required: true,
              message: '请上传附件',
              trigger: 'change',
            },
          ],
          preAuthorizationLetter: [
            {
              required: true,
              message: '请上传附件',
              trigger: 'change',
            },
          ],
        },
      },
    }
  },
  mounted() {
    if (this.type != 'detail') {
      let authorizationStartTime = this.formatDate()
      this.$set(this.form.supplier, 'authorizationStartTime', authorizationStartTime)
    }
  },
  methods: {
    handleInput() {
      const regex = /^[1-9]\d*$/
      if (!regex.test(this.form.supplier.authorizationPeriod)) {
        this.$message({
          type: 'error',
          message: '请输入正整数',
        })
        this.$set(this.form.supplier, 'authorizationPeriod', '')
      } else {
        if (this.form.supplier.authorizationPeriod < 1) {
          this.$set(this.form.supplier, 'authorizationPeriod', 1)
        } else if (this.form.supplier.authorizationPeriod > 360) {
          this.$set(this.form.supplier, 'authorizationPeriod', 360)
        }
      }
    },
    selectGys(row) {
      this.open = false
      this.$set(this.form.supplier, 'supplierName', row.supplierName)
      this.$set(this.form.supplier, 'supplierId', row.supplierId)
    },
    changeGys() {
      this.open = true
      this.getList()
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      getSupplierList(this.queryParamsDig).then((res) => {
        if (res.code == '200') {
          const { rows, total } = res
          this.dataList = rows
          this.total = total
          this.loading = false
        }
      })
    },
    resetQueryDig() {
      this.queryParamsDig = {
        pageNum: 1,
        pageSize: 10,
      }
      this.getList()
    },
    handleQueryDig() {
      this.getList()
    },
    valid() {
      return new Promise(async (resolve) => {
        let result = true
        let refs = Object.values(this.$refs)
        for (let index = 0; index < refs?.length; index++) {
          const ref = refs[index]
          if (Object.prototype.toString.call(ref) == '[object Array]') {
            for (let i = 0; i < ref.length; i++) {
              const element = ref[i]
              if (element?.valid) {
                let rc = await element?.valid?.()
                result = result && rc
              }
              if (element?.validate) {
                let rf = await this._valid(ref)
                result = result && rf
              }
              if (element?.form_validate) {
                let rf = await this._valid(ref, 'form_validate')
                result = result && rf
              }
            }
          } else {
            if (ref?.valid) {
              let rc = await ref?.valid?.()
              result = result && rc
            }
            if (ref?.validate) {
              let rf = await this._valid(ref)
              result = result && rf
            }
            if (ref?.form_validate) {
              let rf = await this._valid(ref, 'form_validate')
              result = result && rf
            }
          }
        }
        resolve(result)
      })
    },
    // 结束时间
    getFutureDate(numDate) {
      const now = new Date()
      now.setDate(now.getDate() + Number(numDate))
      const year = now.getFullYear()
      const month = (now.getMonth() + 1).toString().padStart(2, '0')
      const day = now.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    // 开始时间
    formatDate() {
      let date = new Date()
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    },
  },
}
</script>
<style lang="scss" scoped></style>
